package com.itheima.app.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.login.Configuration;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class UserManager {

    @DubboReference
    UserService userService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    AipFaceTemplate aipFaceTemplate;

    @Autowired
    OssTemplate ossTemplate;

    public ResponseEntity save(User user) {

        Long save = userService.save(user);

        return ResponseEntity.ok(save);
    }

    public ResponseEntity findByone(String phone) {

        User user;

        try {
            user = userService.findByPhone(phone);

        } catch (Exception e) {

            e.printStackTrace();

            return ResponseEntity.status(500).body(ErrorResult.error());
        }

        return ResponseEntity.ok(user);
    }

    public void sendSms(String phone) {

        String code = RandomUtil.randomNumbers(6);

        code = "123456";

        // 2.调用阿里云发送短信
        // smsTemplate.sendSms(phone, code);  // TODO 产品上线后实现短信发送

        // 3.将验证码存入redis

        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));
    }

    public ResponseEntity regAndLogin(String phone, String verificationCode) {

        String code = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);

        if (!StrUtil.equals(verificationCode, code)) {

            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }

        User user = userService.findByPhone(phone);

        boolean isnew;

        if (user != null) {

            isnew = false;

        } else {

            isnew = true;

            user = new User();

            user.setMobile(phone);

            user.setPassword("123456");

            Long byPhone = userService.save(user);

            user.setId(byPhone);
        }

        user.setPassword(null);

        Map<String, Object> map = BeanUtil.beanToMap(user);

        String token = JwtUtil.createToken(map);

       String token1 = JSON.toJSONString(user);

        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, token1, Duration.ofDays(7));

        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        HashMap<String, Object> map1 = new HashMap<>();

        map1.put("isNew", isnew);

        map1.put("token", token);

        return ResponseEntity.ok(map1);
    }

    // 完善用户基本信息
    public void saveUserInfo(UserInfo userInfo, String token) {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        // 2.封装userInfo
        userInfo.setId(user.getId());
        // 3.调用rpc保存
        userInfoService.save(userInfo);
    }

    public User findUserByToken(String token) {
        // 查询redis中的token
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);
        // 空值处理
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 将json转为user对象
        User user = JSON.parseObject(json, User.class);

        // 续期登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));
        // 返回对象
        return user;
    }

    public ResponseEntity saveOrUpdatePhoto(MultipartFile headPhoto, String token) throws IOException {

     //   User userByToken = findUserByToken(token);

       /* if (null == userByToken) {

            return ResponseEntity.status(401).body(null);
        }*/

        User userByToken = UserHolder.get();

        if (!aipFaceTemplate.detect(headPhoto.getBytes())) {

            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }

        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        UserInfo userInfo = new UserInfo();

        userInfo.setId(userByToken.getId());

        userInfo.setAvatar(url);

        userInfo.setCoverPic(url);

        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfoById(Long userID) {

        UserInfo byUserId = userInfoService.findByUserId(userID);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(byUserId, vo);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {

        //User userByToken = findUserByToken(token);

        /*if (null == userByToken) {

            return ResponseEntity.status(401).body(null);
        }*/

        User userByToken = UserHolder.get();

        userInfo.setId(userByToken.getId());

        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }
}
